import BaseComponent from "../../app/baseComponent";
import forEach from "lodash/forEach";

export class AUITabnavs extends BaseComponent {
    constructor(name) {
        super(name);
        this.props = {
            tabs: {
                required: true
            }
        };
        this.methods = {
            setActive(index, cb) {
                this.element.tab.find(`li:eq(${index}) a`).trigger("click");
                if (cb) {
                    cb();
                }
            },
            onLinkClick(e, link, index) {
                e.preventDefault();
                var self = this;
                var tab = "#" + link.href;
                var index = parseFloat(index);
                var el = {};
                if (self.lastactiveIndex != index) {
                    self.tabs[self.lastactiveIndex].active = 0;

                    if (self.tabs[self.lastactiveIndex].href)             
                    {
                        el = document.getElementById(self.tabs[self.lastactiveIndex].href);                       
                        if (el)
                        {
                            el.classList.remove("active");
                            el.classList.remove("in");
                        }
                    }

                    self.tabs[index].active = 1;
                    self.lastactiveIndex = index;

                    if (link.href)             
                    {
                        el = document.getElementById(link.href);                       
                        if (el)
                        {
                            el.classList.add("active");
                            el.classList.add("in");
                        }
                    }
                }
            }
        };
        this._prepend = function () {
            return '';
        };
        this._append = function () {
            return '';
        };
        this._attr = function () {
            return '';
        };
    }
    _data() {
        var ret = {};
        ret.lastactiveIndex = -1;
        return ret;
    }
    _mounted() {
        var self = this;
        forEach(self.tabs, function (v, index) {
            if (v.active) {
                self.lastactiveIndex = index;
            }
        });
    }
    _template() {
        var self = this;
        return `<div class="aui-tabnavs"><slot name="prependul"></slot>
<ul class="aui-tabnavs__tabs" ref="tab" role="tablist" ${self._attr()}>${self._prepend()}<li role="presentation" v-for="tab,index in tabs" class="aui-tabnavs__li" :class="{'active': tab.active}"><a role="tab" 
@click="onLinkClick($event, tab, index)" :index="index" :href="tab.href" v-html="tab.label"></a></li>       
<slot name="appendli"></slot>${self._append()}</ul><slot name="appendul"></slot></div>`;
    }
}

AUITabnavs.install = function () {
    window.AUICustomComponents.define("aui-tabnavs", AUITabnavs);
}